#!/usr/bin/env python
# coding: utf-8 
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.db import GqlQuery
from datetime import date
from models import *
from xml.dom import minidom
from xml.parsers.expat import ExpatError

from hashlib import sha224
from google.appengine.api import memcache
from timeit import Timer
from appengine_utilities.sessions import Session
from datetime import date
import cgi

import re

FIRST_NAME_PATTERN =  re.compile(r"^[\\p{L}]([\\p{Ll}]+)$")
LAST_NAME_PATTERN =  re.compile(r"^(([\\p{L}]([\\p{Ll}]+))*)$")

class MainHandler(webapp.RequestHandler):

	def get(self):
		"""
		FIXME
		"""
		"""
		p = PostIt(task = 'levar o cachorro para passear',
							  description = 'lembrar de levar a coleira',
							  expirationDate = date(2009, 11, 07),
							  stars = 1,
							  container = None).put()
							  
		p = PostIt.all().get()
				
		self.response.out.write('Castor Organizer')
		
		impl = minidom.getDOMImplementation()
		doc = impl.createDocument(None, 'castor', None)
		
		e = getElementFromPostIt(task = "teste", doc = doc, key = str(p.key()))
		
		self.response.out.write(e.toprettyxml())
		
		d = getElementFromDate(tagName = 'startDate', doc = doc)
		
		self.response.out.write(d.toprettyxml())
		"""
		
		data = """
		<data>
			<year>2009</year>
			<month>11</month>
			<day>24</day>
		</data>
		"""
		user = User.all().get()
		p = Project(name = 'castor', owner=user).put()
		c = Container(name = 'To do', project=p).put()
		p = PostIt(task= 'levar o cachorro para passear',
				  startDate = datetime.date.today(),
				  expirationDate = date(2009, 11, 07),
				  stars = 0,
				  container = c).put()
		
		p = User.all().get()
		
		self.response.out.write(p.getAsDOMDocument().toxml())
		


		
					  
class RegisterUserHandler(webapp.RequestHandler):
	def post(self):
		# Getting and cleanning submitted data
		username = self.request.get('username')
		username = cgi.escape(username)
		password = self.request.get('password')
		password = sha224(password).hexdigest() #temporary convertion
		email = self.request.get('email')
		email = cgi.escape(email)
		firstName = self.request.get('firstName')
		firstName = cgi.escape(firstName)
		lastName = self.request.get('lastName')
		lastName = cgi.escape(lastName)
		
		#TODO validate inputs!
		
		# Asking to datastore if there is an user with username OR password given.
		resultName = User.all().filter('username =', username).get()
		resultEmail = User.all().filter('email =', email).get()

		if not (resultName or resultEmail):
			# instantiating user and storing it on database
			user = User(username=username, password = password, email = email, firstName = firstName, lastName = lastName)
			user.put()

			#TODO discover how responses are going to be
			self.response.out.write('Usuario ' + firstName + ' adicionado com sucesso!')

		else:
			#TODO discover how responses are going to be
			self.response.out.write('Usuario ou email ' + username + ' ja existente')
			
	def get(self):
		self.response.out.write("""
				<form action="/register" method="post">
				<label>First Name
				<input type='text' name='firstName' />
				</label>
				
				<label>Last Name
				<input type='text' name='lastName' />
				</label>

				<label>Username
				<input type='text' name='username' />
				</label>
								
				<label>Email
				<input type='text' name='email' />
				</label>
				
				<label>Password
				<input type='password' name='password' />
				</label>
				
				<input type='submit' value='Casastrar' />
			</form>
		""")
		
	
class SyncHandler(webapp.RequestHandler):
	def post(self):
		"""
		FIXMES
		"""
		
		# Getting submited data
		username = self.request.get('username')
		username = cgi.escape(username)
		password = self.request.get('password')
		password = sha224(password).hexdigest() #temporary convertion
		xml = self.request.get('content')
		# TODO xml = cgi.escape(xml)
		
		# Looking for user on database
		user = User.all().filter('username =', username).get()
		
		# Checking if user exists and if its password matches
		if user and user.getPassword() == password:

			user.setContent(xml)
			user.put()		
			self.response.out.write('saved')
			
		else: 

			self.response.out.write('bad-request')	
			
	def get(self):
		"""
		
		"""
		
		self.response.out.write("""
							<html>
								<body>
									<form action="/sync" method="post">
										Username
										<input type="text"     name="username" />
										<br/>
										Password
										<input type="password" name="password" />
										<br/>
										Content
										<textarea name="content"></textarea>
										<br/>
										
										<input type="submit" value="Send" />
									</form>
								</body>
							</html>
							""");
						
class CheckoutHandler(webapp.RequestHandler):
	def post(self):
		"""
		FIXMES
		"""
		
		# Getting submited data
		username = self.request.get('username')
		username = cgi.escape(username)
		password = self.request.get('password')
		password = sha224(password).hexdigest() #temporary convertion
		
		# Looking for user on database
		user = User.all().filter('username =', username).get()
		
		# Checking if user exists and if its password matches
		if user and user.getPassword() == password:

			xml = user.getContent()
			self.response.out.write(xml)
			
		else: 

			self.response.out.write('bad-request')	
			
	def get(self):
		"""
		FIXMES
		"""
		
		self.response.out.write("""
							<html>
								<body>
									<form action="/checkout" method="post">
										<input type="text"     name="username" />
										<input type="password" name="password" />
										
										<input type="submit" value="Send" />
									</form>
								</body>
							</html>
							""");


def main():

  application = webapp.WSGIApplication([('/', MainHandler),
  								('/sync', SyncHandler),
  								('/checkout', CheckoutHandler),
  								('/register', RegisterUserHandler),
  								], 
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
